package flex.cc.util;

import cn.hutool.core.io.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileDownloadUtil {
	
	/**
	 * 通过文件路径下载
	 * @param request
	 * @param response
	 * @param filepath  文件路径
	 */
	public static void downloadByFilepath(HttpServletRequest request,HttpServletResponse response,String filepath) {
		String filename = FileUtil.getName(filepath);
		String new_filename = processFileName(request, filename);
		response.setHeader("Content-Disposition", "attachment;filename=\"" + new_filename + "\"");
    	response.setHeader("FileName", new_filename);
    	response.setHeader("Access-Control-Expose-Headers", "FileName");
    	response.setContentType("application/octet-stream;charset=UTF-8");
    	
    	byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(new File(filepath));
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //下载完之后删除
//	        File delPath = new File(filepath);
//	        if(delPath.exists()){
//	        	delPath.delete();
//	        }
	        int idx = filepath.lastIndexOf(File.separator);
	        String delPath = filepath.substring(0, idx);
	        if (!delPath.endsWith(File.separator)){  
	        	delPath = delPath + File.separator;
	        }
	        File dirFile = new File(delPath); 
	        if (!dirFile.exists() || !dirFile.isDirectory()){  
	            //不处理 
	        }else{
	        	File[] files = dirFile.listFiles();
	        	for (int i = 0; i < files.length; i++){  
	                if (files[i].isFile()){//删除子文件  
	                	files[i].delete();  
	                }else{  //删除子目录  
	                    //此处不会有  
	                }  
	            }
	        	dirFile.delete();
	        }
        }
    }

    /**
     * 通过文件路径下载
     * @param request
     * @param response
     * @param fileName  文件名称
     * @param fileByte  文件字节数组
     */
    public static void downloadByByte(HttpServletRequest request,HttpServletResponse response,String fileName, byte[] fileByte) {
        String new_filename = processFileName(request, fileName);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + new_filename + "\"");
        response.setHeader("FileName", new_filename);
        response.setHeader("Access-Control-Expose-Headers", "FileName");
        response.setContentType("application/octet-stream;charset=UTF-8");

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(fileByte);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }






	
	/**
	 * ie,chrom,firfox下处理文件名显示乱码处理
	 * @param request
	 * @param filename
	 * @return 处理之后的文件名称
	 */
    private static String processFileName(HttpServletRequest request, String filename) {
        String codedfilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                    && -1 != agent.indexOf("Trident")) {// ie
 
                String name = java.net.URLEncoder.encode(filename, "UTF8");
                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
 
                codedfilename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codedfilename;
    }

    /**
     * @Description 根据文件路径及文件名称创建Excel文件
     * @param fileParentPath 文件路径
     * @param fileName 文件名称
     * @return File 返回Excel文件
     */
	public static File createExcelFile(String fileParentPath, String fileName) {
		// 创建文件目录
		File fileParent = new File(fileParentPath);
		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}
		// 根据文件目录创建文件
		String filepath = fileParentPath + File.separator + fileName + ".xlsx";
		File file = new File(filepath);
		if (file.exists()) {
			file.delete();
		}
		return file;
	}

	/**
	 * @description 根据文件路径删除文件
	 * @param filepath 文件路径
	 * @return
	 * @time 2021/07/21 0021 11:23
	 * @exception/throws
	*/
	public static void deleteFileByFilepath(String filepath){
        File file = new File(filepath);
        if (file.exists()){
            file.delete();
        }
    }

	/**
	*
	* @author WANGCONG
	* 2022年3月3日下午15:37:06
	* @desc 图片回传报告下载
	*/
	public static void downloadReport(HttpServletRequest request,HttpServletResponse response,String filepath) {
		String filename = FileUtil.getName(filepath);
		String new_filename = processFileName(request, filename);
		response.setHeader("Content-Disposition", "attachment;filename=\"" + new_filename + "\"");
    	response.setHeader("FileName", new_filename);
    	response.setHeader("Access-Control-Expose-Headers", "FileName");
    	response.setContentType("application/octet-stream;charset=UTF-8");
    	
    	byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(new File(filepath));
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
}
